﻿
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

using YouHP.Utility;
using YouHP.BLL;
using YouHP.Model;
using YouHP.Model.Group;
using System.Web;

namespace YouHP.Pages.BBS
{
    public class TopicAdd:BoardBasePage
    {
        public int MaxFileSize = 1000;
        protected override void ShowPage()
        {
            base.ShowPage();
            if (ErrorCount > 0) return;

            HandleCommon();
            if (ErrorCount > 0) return;

            if (IsPost) HandlePost();
            else HandleGet();
        }

        protected void HandleCommon()
        {
            this.AddLocation("发表帖子", "/BBS/TopicAdd.aspx");
            if (UserData.Id <= 0 || UserData.IsActive==0)
            {
                this.AddErrLine("您还没有登录，请点击先登录！");
                this.MsgboxUrl = this.GetUrl("/User/Login.aspx");
                return;
            }
            UserInfo _User = UserBLL.Instance.GetUserInfo(UserData.Id);
            if ((_User.UserTypeId & 0x100) != 0)
            {
                this.AddErrLine("您已被在本站禁止发言");
                return;
            }
 
        }

        protected void HandlePost()
        {
            TopicInfo topic = ValidateForm();
            string attachedFileAddressName = null;
            string[] tagArr = null;
            if (!string.IsNullOrEmpty(topic.TopicFile))
            {
                attachedFileAddressName = Utils.SaveRequestTopicFile(UserData.Id, MaxFileSize);
                if (attachedFileAddressName.Equals(""))
                {
                    AddErrLine("上传文件失败");
                    return;
                }
            }
            topic.TopicFile = attachedFileAddressName;
            if (ErrorCount > 0) return;
            bool succ = TopicBLL.Instance.AddTopic(topic);
            //获取刚创建的帖子
            TopicInfo TopicData = topic;
            if (succ)
            {
                //添加动态
                UserActionInfo info = new UserActionInfo();
                tagArr = Regex.Split(TopicData.Tags, "\\s+");
                info.UserId = UserData.Id;
                info.UserName = UserData.UserName;
                info.ActionTime = DateTime.Now;
                info.ActionType = Constants.ACTION_TOPIC;
                info.ActionContent = "在论坛版块&nbsp;<a href=\""+this.GetUrl("/BBS/Board.aspx?gid=" + GroupData.Id)+"\" target=\"_blank\">"+GroupData.GroupName+"</a>&nbsp;中发表了帖子&nbsp;<a href=\"" + this.GetUrl("/BBS/Topic.aspx?gid=" + GroupData.Id + "&tid=" + TopicData.Id) + "\"target=\"_blank\">" + TopicData.Title + "</a>&nbsp;";
                UserActionBLL.Instance.AddUserAction(info);

                UserBLL.Instance.UpdateUserCreditsByPost(info.UserId);//设置用户积分
                if (tagArr.Length > 0)
                {
                    if (tagArr[0] != "")
                    {
                    TagBLL.Instance.CreateTopicTag(tagArr, 1, TopicData.Id, info.UserId);
                    }
                }
                this.Redirect(string.Format("/BBS/Board.aspx?gid={0}",GroupData.Id));
            }
            else
            {
                this.AddErrLine("操作失败！");
            }
        }


        protected void HandleGet()
        {


        }

        TopicInfo ValidateForm()
        {
            TopicInfo info = new TopicInfo();

            info.Title = RequestTools.GetFormString("ttitle");
            info.Body = RequestTools.GetFormString("tbody").Trim();
            info.TopicFile = HttpContext.Current.Request.Files[0].FileName;
            if (info.Title.Length == 0)
            {
                this.AddErrLine("标题不能空！");
                return null;
            }
            if (info.Title.Length > Config.TitleMaxSize)
            {
                this.AddErrLine("标题长度不能超过" + Config.TitleMaxSize + "字符！");
                return null;
            }

            if (info.Body.Length == 0)
            {
                this.AddErrLine("内容不能为空！");
                return null;
            }
            else if (info.Body.Length > Config.TopicMaxSize)
            {
                this.AddErrLine("内容长度不能大于 " + Config.TopicMaxSize + "字符！");
                return null;
            }
            info.Groupid = GroupData.Id;
            info.GroupType = GroupData.GroupType;
            info.PostUserId = this.UserData.Id;
            info.PostUserName = this.UserData.UserName;

            info.PostTime = DateTime.Now;
            info.UpdateTime = DateTime.Now;
            info.Sort = RequestTools.GetFormString("TopicSort");
            info.Tags = RequestTools.GetFormString("tags").Trim();

            if (info.Tags == "" && false)
            {
                string tmpTag = "";
                string title = Utils.UrlEncode(Utils.RemoveHtml(Regex.Replace(info.Title, @"\[[^\]]*?\]", string.Empty, RegexOptions.IgnoreCase)));
                string content = Utils.RemoveHtml(Regex.Replace(info.Body, @"\[[^\]]*?\]", string.Empty, RegexOptions.IgnoreCase));
                content = content.Replace(" ", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("\t", string.Empty).Replace("　", string.Empty);
                content = Utils.GetUnicodeSubString(content, 500, string.Empty);
                content = Utils.UrlEncode(content);

                title += content;
                //string xmlContent = Utils.GetSourceTextByUrl(string.Format(" http://search.qihoo.com/sint/related_kw.html?title={0}&content={1}&ics=utf-8&ocs=utf-8", title, content));
                string xmlContent = ""; // ZHI_TODO
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(xmlContent);
                XmlNodeList xnl = xmldoc.GetElementsByTagName("kw");
                StringBuilder builder = new StringBuilder();
                foreach (XmlNode node in xnl)
                {
                    tmpTag += node.InnerText;
                    tmpTag += " ";
                }
                info.Tags = tmpTag.Trim();
            }
            return info;
        }
    }
}